import akshare as ak
import tushare as ts
from datetime import datetime, timedelta
import pandas as pd
import functools
import time
from down_tushare import save_dataframe_as_csv


ts.set_token('2633a6ab6a5142792da59ea91f2204e3b8766bda519eeeae2df1c29c')  # 请替换为你的 token
pro = ts.pro_api()

def get_dc_cyp_chips(filename_prefix='', path="F:/Personal/data/"):

    # 使用函数名作为文件名的一部分
    func_name = "dc_cyp_chips"

    # 初始化一个空的列表来存储结果
    data_list = []

    # 将字符串转换为datetime对象
    trade_date = datetime.now().strftime('%Y%m%d')

    # 股票基础信息
    secu_df = pro.stock_basic(trade_date=trade_date)

    date_info = ""

    trade_date = datetime.now().strftime('%Y%m%d')
    for index, row in secu_df.iterrows():
        ts_code = row['ts_code'][:-3]
        print(ts_code)
        # print(ts_code, trade_dt.strftime('%Y%m%d'))
        # 调用传入的数据源函数获取数据（日期范围）
        single_secu_data_df = ak.stock_cyq_em(symbol=ts_code, adjust="qfq")
        data_list.append(single_secu_data_df)

    combined_df = pd.DataFrame()
    if data_list:

        # 将当天的所有证券信息何必为一个大DataFrame
        combined_df = pd.concat(data_list, ignore_index=True)

        # 设置文件名前缀
        filename_prefix = func_name

        # 构建日期信息
        date_info = trade_date

    if not data_list:
        print(f"{data_func} does not get data found on the {trade_date}.")
        return None

    # 检查DataFrame是否为空（例如，没有行）
    if combined_df.empty:
        print(f"{data_func} does not get data found on the {trade_date}.")
        return None

    # 保存DataFrame到CSV
    if not filename_prefix:
        filename_prefix = func_name

    save_dataframe_as_csv(combined_df, filename_prefix, date_info, path)

    return combined_df

get_dc_cyp_chips()